//
//  GoodsDetailViewController.m
//  FD
//
//  Created by xiaofang wang on 2018/12/7.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//
//tableView + 嵌套collectionView
#import "GoodsDetailViewController.h"

//view
#import "GoodsDetailHeaderView.h" //表头
#import "HomeGoodsDetailRemarkView.h" //表尾
#import "HomeGoodsDetailTableViewCell.h" //12-21cell中嵌套collectionView
#import "HomeGoodsDetailBottomView.h" //底部加入购物车view

//model
#import "HomeGoodsDetailBigModel.h"
#import "HomeGoodsDetailModel.h"
#import "HomeGoodsDetailHeaderModel.h" //表头model

//tool
#import "FDSystemTool.h" //振动

@interface GoodsDetailViewController ()<UITableViewDelegate,
UITableViewDataSource,
HomeGoodsDetailTableViewCellDelegate //更新商品总价
>

/**1.tableView*/
@property (nonatomic, strong) UITableView *tableView;
/**2.表头*/
@property (nonatomic, strong) GoodsDetailHeaderView *headerview;
/**3.表尾*/
@property (nonatomic, strong) HomeGoodsDetailRemarkView *footerRemarkView;
/**4.bottomView*/
@property (nonatomic, strong) HomeGoodsDetailBottomView *bottomView;
/**5.配料数据源数据源, 请先创建容器*/
@property (nonatomic, strong) NSMutableArray *ingredientClsArrM;
/**6.记录主食价格*/
@property (nonatomic) CGFloat staplePrice;
/**2019-2-16记录原价价格*/
@property(nonatomic) CGFloat tempOriginPrice;



@end

@implementation GoodsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self requestGoodsDetailData];
    
    [self setupUI];
}

- (void)setupUI {
    
    //1.导航条
//    self.navigationItem.title = @"商品详情";
    if ([NSString rb_ChineseLanguage]) {
        self.navigationItem.title = @"加载中";
    }else {
        self.navigationItem.title = @"Loading";
    }
    
    self.view.backgroundColor = [UIColor whiteColor];

    //2.设置talbeView的frame
    CGRect tvFrame = self.view.bounds;
    tvFrame.size.height = SCREEN_HEIGHT - 40 - FD_TabbarSafeBottomMargin;
    self.tableView.frame = tvFrame;
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerview;
    self.tableView.tableFooterView = self.footerRemarkView;
    self.tableView.estimatedRowHeight = 100.f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    //3.添加底部bottomView
    [self.view addSubview:self.bottomView];
}


#pragma mark - getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        //代理
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //注册cell
        [_tableView registerClass:[HomeGoodsDetailTableViewCell class] forCellReuseIdentifier:@"HomeGoodsDetailTableViewCell"];
        
        //取消内容线
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}

- (GoodsDetailHeaderView *)headerview {
    if (!_headerview) {
        
        CGFloat h = 70+FDScaleWidth(250);
        
        _headerview = [[GoodsDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, h)]; //
        //获取到网页的高度的回调,
        //干什么:更新_headerview高度 & 显示网页
        FDWeakSelf;
        _headerview.goodsDetailHeaderViewHeightBlock = ^(CGFloat height) {
            weakSelf.headerview.bounds = CGRectMake(0, 0, SCREEN_WIDTH, h + height*1.2);
            [weakSelf.tableView reloadData]; //属性表格
        };
    }
    return _headerview;
}
- (HomeGoodsDetailRemarkView *)footerRemarkView {
    if (!_footerRemarkView) {
        _footerRemarkView = [[HomeGoodsDetailRemarkView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
    }
    return _footerRemarkView;
}

//!!!!:加入购物车
- (HomeGoodsDetailBottomView *)bottomView {
    if (!_bottomView) {
        //iphoneX
        CGFloat y = (SCREEN_HEIGHT - FD_TabbarSafeBottomMargin-40);
        _bottomView = [[HomeGoodsDetailBottomView alloc] initWithFrame:CGRectMake(0, y, SCREEN_WIDTH, 40)];
        
        FDWeakSelf;
        _bottomView.clickAddCartBlock = ^(NSInteger cnt) {
            if (cnt <1) {
                FDLog(@"数量不能为0");
                return ;
            }
            [weakSelf requestAddCartFeiTaoCanGoodsId:weakSelf.goodsId quantity:@(cnt)];
        };
    }
    return _bottomView;
}

- (NSMutableArray *)ingredientClsArrM {
    if (!_ingredientClsArrM) {
        _ingredientClsArrM = [NSMutableArray array];
    }
    return _ingredientClsArrM;
}


#pragma mark - UITableViewDelegate UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HomeGoodsDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeGoodsDetailTableViewCell"];
    
    cell.delegate = self; //设置代理 HomeGoodsDetailTableViewCellDelegate
    [cell hgdtcellReloaddataWithIngredientClassifyListArr:self.ingredientClsArrM.copy]; //设置数据
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    FDLog(@"%lu",(unsigned long)self.ingredientClsArrM.count);
    
    CGFloat height = [self countCellHeightWithIngredientClassifyArr:self.ingredientClsArrM.copy];
    
    FDLog(@"1111高度:%f",height);
    return height;
}


#pragma mark - 网络请求
//两次网络请求:请求商品详情数据
- (void)requestGoodsDetailData {
    if(!self.goodsId) return;
    
    //
    CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
    // do something

    FDLog(@"当前线程:%@",[NSThread currentThread]);
    
    //一:请求
    [FDHttpAPi requestGoodsDetailWithGoodsId:self.goodsId Block:^(id responseObjc) {
        FDLog(@"当前线程:%@",[NSThread currentThread]);

        //判断是否请求成功
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:@"SUCCESS"]) { //请求成功，解析数据
            
            //2. 解析数据
            [self assebmleGoodsDetailDataWithResponDic:responseObjc];
            
            
            //2-2.记录主食价格 &2-16原价
            NSNumber *currentPrice = responseObjc[@"data"][@"currentPrice"];
            NSNumber *originPrice = responseObjc[@"data"][@"originalPrice"];
            
            self.staplePrice = [currentPrice floatValue];
            self.tempOriginPrice = [originPrice floatValue];

            //线刷新一下,不然cell里的collectionView不显示
            [self.tableView reloadData]; //刷新一下
            
            //3. 12-6 下载商品详情模板内容 html 字符串
            [FDAWSDownUpLoadTool fdAWSDownloadWithKey:responseObjc[@"data"][@"richtext"] complectionBlock:^(NSString * _Nonnull resultStr) {
                //4.加载网页内容模板
                CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
                FDLog(@"来了,耗时... : %f", end - start); //2.348965
                
                //5.加载网页 网页加载成功之后会需要再次进行刷新
                [self.headerview headerViewLoadwebviewWithContentHtmlStr:resultStr];
                
                //12-7tips:数据都是异步的(1.请求商品详情数据,2.加载网页数据),这里不刷新, 只有等到表头网页加载出来之后,算出网页的高度之后,会有一个回调,在回调的方法中进行刷新
            } failBlock:^{
                
                
            }];
           

        }else if ([event isEqualToString:@"ERROR"]) { //失败，弹toast
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        
    }];
}

//解析数据
- (void)assebmleGoodsDetailDataWithResponDic:(NSDictionary *)responDic {
    NSDictionary *dataDic = responDic[@"data"];

    self.navigationItem.title = dataDic[@"title"]; //@"商品详情";

    
    
    //1.组装表头数据
    HomeGoodsDetailHeaderModel *headerModel = [HomeGoodsDetailHeaderModel mj_objectWithKeyValues:dataDic];
    self.headerview.model = headerModel; //更新表头数据
    
    
    //2019-1-17如果有默认值,需要加上默认值,垃圾代码就是这样写出来的，
    NSNumber *sumCurrentPriceNum = @([headerModel.currentPrice floatValue] + [headerModel.defaultSelectPrice floatValue]);
    NSNumber *sumOriPriceNum = @([headerModel.originalPrice floatValue] + [headerModel.defaultSelectPrice floatValue]);
    [self.bottomView updateOriginPrice:sumOriPriceNum discountPrice:sumCurrentPriceNum];//第一次要显示的价格
    
    [self.headerview updateGoodsDetailHeaderViewSumCurrentPrice:[sumCurrentPriceNum floatValue] sumOriginPrice:[sumOriPriceNum floatValue]]; //2019-2-16 更新原价数据

    
    //2.组装其他数据
    [self assembleDetailModelWithArr:dataDic[@"ingredientClassifyList"]];
}

- (void)assembleDetailModelWithArr:(NSArray *)ingredientClassifyList {
    //空数组则不解析
    if (ingredientClassifyList.count == 0) return;
    
    //一 先转成模型
    for (NSDictionary *outDic in ingredientClassifyList) {
        //数组:内部元素转为dic
        HomeGoodsDetailBigModel *bigModel = [HomeGoodsDetailBigModel mj_objectWithKeyValues:outDic];
        [self.ingredientClsArrM addObject:bigModel];
    }
    
    
    //二 给内部的model的  only 、 defaultSelect赋值
    for (HomeGoodsDetailBigModel *bigM2 in self.ingredientClsArrM) {
        NSNumber *only = bigM2.only;
        NSNumber *defaultSelected = bigM2.defaultSelect;
        
        //给所有的小model的only 、 defaultSelect进行赋值
        for (HomeGoodsDetailModel *smallM  in bigM2.ingredientList) {
            smallM.only = only;
            smallM.defaultSelect = defaultSelected;
        }
    }
}

//!!!!:加入购物车网络请求

//加入购物车接口
- (void)requestAddCartFeiTaoCanGoodsId:(NSNumber *)goodId quantity:(NSNumber *)quantity {
    //组装请求参数
    
    //一参数1：goodsIngredientList
    NSMutableArray *tagIdArrM = @[].mutableCopy;
    //便利数据源,取出所有选中标签id
    for (HomeGoodsDetailBigModel *bigM in self.ingredientClsArrM) {
        
        NSArray *ingredientArr = bigM.ingredientList;
        //二次便利
        for (HomeGoodsDetailModel *smallM in ingredientArr) {
            
            //如果isSelect就保存
            //如果不点就用默认的。
            //表示默认选中 [smallM.tagId isEqualToNumber:smallM.defaultSelect]、
            //点击之后就修改就将defaultSelect 设置为-1.表示未选中
            
            if (smallM.isSelected || [smallM.tagId isEqualToNumber:smallM.defaultSelect]) {
                [tagIdArrM addObject:smallM.tagId];
            }
        }
    }
    
    //    if (!tagIdArrM.count) return;
    
    FDLog(@"%@",tagIdArrM);
    
    //参数2: goodsId
    //参数3: 评论 remark
    NSString *remark = self.footerRemarkView.tf.text ? : @""; //有值就是自己，没值就是空
    //参数4: 数量 quantity
    
    NSDictionary *parDic = @{@"goodsIngredientList":tagIdArrM,
                             @"goodsId":goodId,
                             @"remark":remark,
                             @"quantity":quantity
                             };
    
    [FDHttpAPi requesSYUserCartAddWithParDic:parDic successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            [JRToast showWithText:NSLocalizedString(ToastAddCartSuccess, @"成功加入购物车")];

            //振动
            [FDSystemTool fd_virbrate];
            //返回
            [self.navigationController popViewControllerAnimated:YES];
            
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
        
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}
#pragma mark - 计算cell高度(权宜之计)
- (CGFloat )countCellHeightWithIngredientClassifyArr:(NSArray *)ingredientClassifyArr {
    //section 的宽:40
    CGFloat sectionH = 40;
    //item 的宽 40
    CGFloat itemH = 40; //; //2019-2-13 itemh=40 需要取出collection上下item之间的间距
    
    CGFloat sumHeight = 0;
    sumHeight += ingredientClassifyArr.count * sectionH;
    
    for (HomeGoodsDetailBigModel *bigM in ingredientClassifyArr) {
        //+1 防止为奇数的时候,少一行
        sumHeight += ((bigM.ingredientList.count + 1) / 2) * itemH;
    }
    
    FDLog(@"cell总高度:%f",sumHeight);
    return sumHeight;
}




//- (CGFloat )countCellHeightWithIngredientClassifyArr:(NSArray *)ingredientClassifyArr {
//    //section 的宽:40
//    CGFloat sectionH = 40;
//    //item 的宽 40
//    CGFloat itemH = 40;
//
//    CGFloat sumHeight = 0;
//    sumHeight += ingredientClassifyArr.count * sectionH;
//
//    for (HomeGoodsDetailBigModel *bigM in ingredientClassifyArr) {
//        //+1 防止为奇数的时候,少一行
//        sumHeight += ((bigM.ingredientList.count + 1)/ 2) * itemH;
//    }
//
//    //2019-1-19 fix bug 特殊情况:都是奇数会出问题.
//    if (ingredientClassifyArr.count == 1) {
//        sumHeight += itemH * 0.5;
//    }
//
//    FDLog(@"cell总高度:%f",sumHeight);
//
//    return sumHeight;
//
//    //2019-2-12
//    //数组中最后一个数元素的个数如果为0或1 不加itemH; 反之加
//    HomeGoodsDetailBigModel *lastBigM = [ingredientClassifyArr lastObject];
//    if (lastBigM.ingredientList.count <=2) { //防止间距过大
//        return sumHeight;
//    }else { //防止多出来的一个被盖住
//        return sumHeight + itemH;
//    }
//
//    //2019-2-13 特别不的时候还是显示不全
////    return sumHeight + itemH;
////    return 500;
//}

#pragma mark - 代理 HomeGoodsDetailTableViewCellDelegate 用于更新总价
//请加上主食的价格
- (void)didCalculateIngredientTotalPrice:(CGFloat)ingredientSumPrice {
    
    CGFloat sp = self.staplePrice + ingredientSumPrice;
    CGFloat sOriginPrice = self.tempOriginPrice + ingredientSumPrice;//2019-2-16
    
    //更新表头商品价格
    [self.headerview updateGoodsDetailHeaderViewSumCurrentPrice:sp sumOriginPrice:sOriginPrice];
    
    //更新底部价格
    [self.bottomView updateOriginPrice:@(sOriginPrice) discountPrice:@(sp)];
}
//12-21 新加
- (void)didSelectIngredientTagArr:(NSArray *)ingredientTagArr singleSelTag:(NSNumber *)tagId {
    FDLog(@"标签tagId:%@ 数量:%ld",ingredientTagArr,ingredientTagArr.count);
}
@end
